<?php

class Application_Model_CourseDAO
{
	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if(is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if(!$dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
 
	public function getDbTable()
	{
		if(null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Course');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Course $course)
	{
		$data = array(
			'GPNUM' => $course->getGpNum(),
			'PILNUM' => $course->getPilote()->getPilNum(),
			'TEMPSCOURSE' => $course->getTempsCourse()
		);
 		try
 		{
			$this->getDbTable()->insert($data);
			return true;
 		}
 		catch(Exception $e)
 		{
			return false;
 		}
	}
	
	public function find($gpNum, $pilNum)
	{
		$course = new Application_Model_Course();

		$result = $this->getDbTable()->find($gpNum, $pilNum);
		if(0 == count($result))
		{
			return null;
		}
		$row = $result->current();
		$course->setGpNum($row->GPNUM)
			   ->setTempsCourse($row->TEMPSCOURSE);
				  
		//On recupere le pilote
		$piloteDAO = new Application_Model_PiloteDAO();
		$pilote = $piloteDAO->find($row->PILNUM);
		$course->setPilote($pilote);
		
		return $course;
	}
	
	public function findAll()
	{
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->from('course',array('GPNUM', 'PILNUM'))->order('TEMPSCOURSE ASC'));
		$entries = array();
		foreach($resultSet as $row)
		{
			$entries[] = $this->find((int)$row->GPNUM, (int)$row->PILNUM);
		}
		return $entries;
	}
	
	public function findByGrandprix($gpNum)
	{
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->from('course',array('GPNUM', 'PILNUM'))->where('GPNUM = '.$gpNum)->order('TEMPSCOURSE ASC'));
		$entries = array();
		foreach($resultSet as $row)
		{
			$entries[] = $this->find((int)$row->GPNUM, (int)$row->PILNUM);
		}
		return $entries;
	}
}